/*
 * condition.cpp
 *
 *  Created on: 2008-12-15
 *      Author: fanliangliang
 */

#include "condition.h"

BEGIN_NAMESPACE_TOXIC

Condition::Condition() {
	pthread_cond_init(&_condition, 0);
}

Condition::~Condition() {
	pthread_cond_destroy(&_condition);
}

void Condition::wait(ScopedLock& lock) {
	pthread_cond_wait(&_condition, lock.internal());
}

bool Condition::wait(ScopedLock& lock, unsigned long millisecond) {
	struct timespec ts;
	makeTimeout(&ts, millisecond);
	int result = pthread_cond_timedwait(&_condition, lock.internal(), &ts);
	if (result == 0) {
		return true;
	}
	else /*if (result == ETIMEOUT)*/ {
		return false;
	}
}

void Condition::notify(){
	pthread_cond_signal(&_condition);
}

void Condition::notifyAll() {
	pthread_cond_broadcast(&_condition);
}

void Condition::makeTimeout(struct timespec* pts, unsigned long millisecond) {
	struct timeval tv;
	gettimeofday(&tv, 0);

	pts->tv_sec = millisecond / 1000 + tv.tv_sec + (millisecond % 1000 + tv.tv_usec / 1000) / 1000;
	pts->tv_nsec = (millisecond % 1000 * 1000 + tv.tv_usec) % 1000000 * 1000;
}

END_NAMESPACE_TOXIC
